package cn.springcloud.fix.uaa.web.service.impl;

import cn.springcloud.fix.common.cache.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.RandomValueAuthorizationCodeServices;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * 自定义AuthorizationCodeServices，把code存在缓存里
 */
@Slf4j
@Service
public class MyAuthorizationCodeServices extends RandomValueAuthorizationCodeServices {

    @Autowired
    private RedisService redisService;

    /**
     * 替换JdbcAuthorizationCodeServices的存储策略
     * 将存储code到redis，并设置过期时间，10分钟
     */
    @Override
    protected void store(String code, OAuth2Authentication authentication) {
        redisService.set(redisKey(code), authentication, 10, TimeUnit.MINUTES);
    }

    @Override
    protected OAuth2Authentication remove(String code) {
        String key = redisKey(code);
        OAuth2Authentication token = redisService.get(key);
        redisService.deleteKey(key);
        return token;
    }

    /**
     * redis中 code key的前缀
     */
    private String redisKey(String code) {
        return "oauth:code:" + code;
    }
}
